package com.laicunba.ext.web.controller.console;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.laicunba.ext.service.SlaveQueryService;
import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.service.TemplateService;
import com.laicunba.util.ExcelUtil;
import com.laicunba.util.StringUtil;

@Controller
public class DataExportController extends BaseController {

	@Autowired
	private SlaveQueryService slaveQueryService;
	@Autowired
	private TemplateService templateService;

	@RequestMapping(value = "/console/ext/data_export.htm")
	public void dataExport(HttpServletRequest request, HttpServletResponse response, String selectSql, String id) {

		// 将文件存到指定位置
		OutputStream out = null;
		try {

			if (StringUtil.isNotEmpty(id)) {
				TemplateDO tmp = templateService.get(TemplateDO.class, id);
				if (tmp != null) {
					JSONObject json = (JSONObject) new JSONParser().parse(tmp.getContent());
					selectSql = (String) json.get("sql");
				}
			}

			List<Map<String, Object>> data = slaveQueryService.executeSelect(URLDecoder.decode(selectSql.trim(), "utf-8"));
			ByteArrayOutputStream stream = ExcelUtil.generate(data);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("content-disposition", "attachment;filename=" + StringUtil.genGUID() + ".xls");
			out = response.getOutputStream();
			out.write(stream.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
